const express = require('express');
const router = express.Router();
const rds = require('../rds');
const logger = require('../logger');

// 活动列表页面
router.get('/', async (req, res) => {
    try {
        const [activities] = await rds.query(
            'SELECT *, DATE_FORMAT(FROM_UNIXTIME(start_time), "%Y-%m-%d %H:%i") as start_time_fmt, DATE_FORMAT(FROM_UNIXTIME(end_time), "%Y-%m-%d %H:%i") as end_time_fmt FROM eb_lottery_activities ORDER BY add_time DESC'
        );

        res.render('activity/list', {
            activities,
            title: '活动管理',
            description: '管理抽奖活动'
        });
    } catch (error) {
        logger.error('Error fetching activities:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取活动列表失败',
            description: error.message
        });
    }
});

// 新建活动页面
router.get('/new', (req, res) => {
    res.render('activity/edit', {
        activity: {
            activity_code: '',
            activity_name: '',
            activity_description: '',
            start_time: '',
            end_time: '',
            max_rounds: 1,
            cost_points: 0,
            conditions: 'true'
        },
        isNew: true,
        title: '创建新活动',
        description: '创建新的抽奖活动'
    });
});

// 编辑活动页面
router.get('/edit/:activity_code', async (req, res) => {
    try {
        const { activity_code } = req.params;
        const [activities] = await rds.query(
            'SELECT *, DATE_FORMAT(FROM_UNIXTIME(start_time), "%Y-%m-%dT%H:%i") as start_time_fmt, DATE_FORMAT(FROM_UNIXTIME(end_time), "%Y-%m-%dT%H:%i") as end_time_fmt FROM eb_lottery_activities WHERE activity_code = ?',
            [activity_code]
        );

        if (activities.length === 0) {
            return res.status(404).render('warn', {
                title: '活动不存在',
                message: '未找到该活动',
                description: `活动代码: ${activity_code}`
            });
        }

        // 格式化landing_config为美化的JSON字符串
        let landing_config = '{}';
        try {
            const config = JSON.parse(activities[0].landing_config || '{}');
            landing_config = JSON.stringify(config, null, 4);
        } catch (e) {
            logger.error('Error parsing landing_config:', e);
        }

        // 获取活动奖品
        const [prizes] = await rds.query(
            'SELECT * FROM eb_lottery_prizes WHERE activity_code = ?',
            [activity_code]
        );

        res.render('activity/edit', {
            activity: activities[0],
            prizes,
            landing_config,
            isNew: false,
            title: '编辑活动',
            description: `活动代码: ${activity_code}`
        });
    } catch (error) {
        logger.error('Error fetching activity:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取活动详情失败',
            description: error.message
        });
    }
});

// 查看活动结果
router.get('/results/:activity_code', async (req, res) => {
    const { activity_code } = req.params;

    try {
        // 在此处查询特定抽奖活动的所有抽奖结果
        const sql = `SELECT r.uid, u.real_name as name, u.promoter_type as type, u.rep_code, u.phone, r.prize_name as prize, r.memo, r.comment, DATE_FORMAT(FROM_UNIXTIME(r.lottery_time), '%Y-%m-%d %H:%i:%s') AS drawed_at from eb_user_lottery_results r left join eb_user u on (r.uid = u.uid) WHERE prize_id in ( select prize_id from eb_lottery_prizes where activity_code = '${activity_code}' ) order by r.prize_id asc, rep_code asc, id desc`;
        const [lotteryResults] = await rds.query(sql);
        const downloadLink =
            req.session.crmROLE == "crm-admin" ||
            req.session.crmROLE == "crm-gmoffc"
                ? `
            <span><a href="https://totemlife.cn/apps/download-excel?sql=${encodeURIComponent(sql)}&filename=${activity_code}-report.xls"><span class="fas fa-download"></i></a></span>
        `
                : "";

        // 渲染列出抽奖结果的页面，并将数据传递给模板
        res.render("loyalty/lottery-results", { lotteryResults, downloadLink });
    } catch (error) {
        console.error("Error fetching lottery results:", error);
        res.status(500).json({ message: "Internal Server Error" });
    }
    /*
    try {
        const { activity_code } = req.params;
        const [activity] = await rds.query(
            'SELECT * FROM eb_lottery_activities WHERE activity_code = ?',
            [activity_code]
        );

        if (activity.length === 0) {
            return res.status(404).render('warn', {
                title: '活动不存在',
                message: '未找到该活动',
                description: `活动代码: ${activity_code}`
            });
        }

        // 获取中奖记录
        const [results] = await rds.query(`
            SELECT 
                w.*,
                u.real_name,
                p.prize_name,
                DATE_FORMAT(FROM_UNIXTIME(w.add_time), '%Y-%m-%d %H:%i') as win_time
            FROM eb_lottery_winners w
            LEFT JOIN eb_user u ON w.uid = u.uid
            LEFT JOIN eb_lottery_prizes p ON w.prize_id = p.id
            WHERE w.activity_code = ?
            ORDER BY w.add_time DESC
        `, [activity_code]);

        res.render('activity/results', {
            activity: activity[0],
            results,
            title: '活动结果',
            description: `${activity[0].activity_name} - 中奖记录`
        });
    } catch (error) {
        logger.error('Error fetching activity results:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取活动结果失败',
            description: error.message
        });
    }
    */
});

// 保存活动信息
router.post('/', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const {
            activity_code,
            activity_name,
            activity_description = '',
            start_time,
            end_time,
            max_rounds = 1,
            cost_points = 0,
            conditions = 'true',
            isNew,
            landing_config = '{}'
        } = req.body;

        // 验证landing_config是否为有效的JSON
        try {
            JSON.parse(landing_config);
        } catch (e) {
            throw new Error(`启动页配置JSON格式无效: ${e.message}`);
        }

        // 验证必填字段
        if (!activity_code || !activity_name || !start_time || !end_time) {
            throw new Error('活动代码、名称、开始时间和结束时间为必填项');
        }

        // 转换时间格式
        const startTimestamp = Math.floor(new Date(start_time).getTime() / 1000);
        const endTimestamp = Math.floor(new Date(end_time).getTime() / 1000);
        const now = Math.floor(Date.now() / 1000);

        if (endTimestamp <= startTimestamp) {
            throw new Error('结束时间必须晚于开始时间');
        }

        if (isNew === "true") {
            // 检查活动代码是否已存在
            const [existing] = await connection.query(
                'SELECT 1 FROM eb_lottery_activities WHERE activity_code = ?',
                [activity_code]
            );

            if (existing.length > 0) {
                throw new Error('活动代码已存在');
            }

            // 插入新活动
            await connection.query(
                `INSERT INTO eb_lottery_activities 
                (activity_code, activity_name, activity_description, start_time, end_time, 
                max_rounds, cost_points, conditions, landing_config, add_time)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [activity_code, activity_name, activity_description, startTimestamp, endTimestamp,
                max_rounds, cost_points, conditions, landing_config, now]
            );
        } else {
            // 更新现有活动
            await connection.query(
                `UPDATE eb_lottery_activities 
                SET activity_name = ?, activity_description = ?, start_time = ?, 
                    end_time = ?, max_rounds = ?, cost_points = ?, conditions = ?,
                    landing_config = ?
                WHERE activity_code = ?`,
                [activity_name, activity_description, startTimestamp, endTimestamp,
                max_rounds, cost_points, conditions, landing_config, activity_code]
            );
        }

        await connection.commit();
        res.redirect('/apps/admin/activities');
    } catch (error) {
        await connection.rollback();
        logger.error('Error saving activity:', error);

        // 增强错误信息的显示
        let errorMessage = error.message;
        if (error.sql) {
            // 如果是数据库错误，添加SQL错误信息
            errorMessage += `\nSQL Error: ${error.sqlMessage || '未知数据库错误'}`;
        }

        res.status(500).render('warn', {
            title: '系统错误',
            message: '保存活动失败',
            description: errorMessage || '请检查必填字段是否填写完整'
        });
    } finally {
        connection.release();
    }
});

// 修改奖品保存路由
router.post('/prize', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const {
            prize_id,
            activity_code,
            prize_name,
            prize_tips = '',
            initial_quantity,
            remaining_quantity,
            auto_grant_type = 0,
            grant_options = '{}',
            isNew
        } = req.body;

        // 验证必填字段
        if (!activity_code) {
            throw new Error('活动代码不能为空');
        }
        if (!prize_name) {
            throw new Error('奖品名称不能为空');
        }
        if (!initial_quantity || initial_quantity === '') {
            throw new Error('初始数量不能为空');
        }
        if (!remaining_quantity || remaining_quantity === '') {
            throw new Error('剩余数量不能为空');
        }

        // 转换为数字类型
        const initialQty = parseInt(initial_quantity, 10);
        const remainingQty = parseInt(remaining_quantity, 10);
        const autoGrantType = parseInt(auto_grant_type, 10);

        // 验证数值
        if (isNaN(initialQty) || isNaN(remainingQty)) {
            throw new Error('数量必须是有效的数字');
        }
        if (initialQty < 0 || remainingQty < 0) {
            throw new Error('数量不能为负数');
        }

        // 验证 grant_options 格式
        let grantOptionsJson = grant_options;
        try {
            if (typeof grant_options === 'string') {
                JSON.parse(grant_options); // 验证JSON格式
            } else {
                grantOptionsJson = JSON.stringify(grant_options);
            }
        } catch (error) {
            throw new Error('发放选项必须是有效的JSON格式');
        }

        if (isNew === "true") {
            // 插入新奖品
            await connection.query(
                `INSERT INTO eb_lottery_prizes 
                (activity_code, prize_name, prize_tips, initial_quantity, remaining_quantity, 
                auto_grant_type, grant_options, add_time)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
                [activity_code, prize_name, prize_tips, initialQty, remainingQty, 
                autoGrantType, grantOptionsJson, Math.floor(Date.now() / 1000)]
            );
        } else {
            // 更新现有奖品
            await connection.query(
                `UPDATE eb_lottery_prizes 
                SET prize_name = ?, prize_tips = ?, initial_quantity = ?, remaining_quantity = ?,
                auto_grant_type = ?, grant_options = ?
                WHERE prize_id = ? AND activity_code = ?`,
                [prize_name, prize_tips, initialQty, remainingQty, 
                autoGrantType, grantOptionsJson, prize_id, activity_code]
            );
        }

        await connection.commit();

        if (req.headers.accept && req.headers.accept.includes('application/json')) {
            res.json({
                success: true,
                message: '保存成功',
                redirectUrl: `/apps/admin/activities/edit/${activity_code}`
            });
        } else {
            res.redirect(`/apps/admin/activities/edit/${activity_code}`);
        }
    } catch (error) {
        await connection.rollback();
        logger.error('Error saving prize:', error);

        if (req.headers.accept && req.headers.accept.includes('application/json')) {
            res.status(500).json({
                success: false,
                message: error.message || '保存奖品失败，请检查必填字段是否填写完整'
            });
        } else {
            res.status(500).render('warn', {
                title: '系统错误',
                message: '保存奖品失败',
                description: error.message || '请检查必填字段是否填写完整'
            });
        }
    } finally {
        connection.release();
    }
});

module.exports = router; 
